package HLCode.ASM.value;

import HLCode.HLCustomFunction;
import HLCode.HLCustomFunction_H;
import HLCode.HLObject;

public class ASM_Int implements HLCustomFunction_H {
    byte type;

    int immediateValue;

    byte[] links;

    byte index;

    public int Load(byte[] data, int pos) {
        type = data[pos++];
        switch (type) {
        case OWNER_OBJECT_TYPE_IMMEDIATE_BYTE: {
            immediateValue = data[pos++];
            type = OWNER_OBJECT_TYPE_IMMEDIATE_INT;
            break;
        }
        case OWNER_OBJECT_TYPE_IMMEDIATE_SHORT: {
            immediateValue = (short) ((data[pos] & 0xff) | ((data[pos + 1] << 8) & 0xff00));
            pos += 2;
            type = OWNER_OBJECT_TYPE_IMMEDIATE_INT;
            break;
        }
        case OWNER_OBJECT_TYPE_IMMEDIATE_INT: {
            immediateValue = (data[pos] & 0xff) | ((data[pos + 1] << 8) & 0xff00) | ((data[pos + 2] << 16) & 0xff0000) | ((data[pos + 3] << 24) & 0xff000000);
            pos += 4;
            break;
        }
        default: {
            int levelCount = data[pos++];
            links = new byte[levelCount];
            System.arraycopy(data, pos, links, 0, levelCount);
            pos += levelCount;
            index = data[pos++];
        }
        }
        return pos;
    }

    public int GetValue(HLCustomFunction ownerFunction) {
        if (type == OWNER_OBJECT_TYPE_IMMEDIATE_INT) {
            return immediateValue;
        } else {
            HLObject valueOwnerObject = ownerFunction.ownerObjectGroup[type];
            for (int i = 0; i < links.length; i++) {
                valueOwnerObject = valueOwnerObject.GetObject(links[i]);
            }
            return valueOwnerObject.GetInt(index);
        }
    }
}
